package com.nicefact.util;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

public class StringUtil {

	public static String getUserNameOutOfEmail(String email) {
		return StringUtils.split(email, "@")[0];
	}

	public static String generateUrl(String url,
			Map<String, String> parameterList, List<String> tokens) {

		Set<String> keyList = parameterList.keySet();
		
		//assigning url into newUrl
		StringBuffer newUrl = new StringBuffer();
		newUrl.append(url);
		
		/*
		 * check if tokens already exist then append new tokens
		 * else
		 * append '/' sign and add tokens
		 * 
		 */
		if (StringUtils.isNotBlank(url)) {
			char ch = url.charAt(url.length() - 1);
			if (ch != '/') {
				newUrl.append('/');
			}
			if (tokens != null && !(tokens.isEmpty()))
				for (String token : tokens) {
					newUrl.append(token).append('/');
				}
		}
		
		char ch = newUrl.charAt(newUrl.length() - 1);
		if (ch != '/') {
			newUrl.append("?");
		} else {
			newUrl.setCharAt(newUrl.length() - 1, '?');
		}
		
		/*
		 * adding parameters from paramaterList
		 */
		boolean firstRecord = true;
		Iterator<String> keyListIterator = keyList.iterator();
		do {
			String value = keyListIterator.next();

			if (firstRecord) {
				firstRecord = false;
			} else {
				newUrl.append('&');
			}

			newUrl.append(value).append("=").append(parameterList.get(value));
		} while (keyListIterator.hasNext());
		url = newUrl.toString();
		return url;
	}
}
